// edit.js
const api = require('../../../utils/api')

Page({
  data: {
    address: {
      id: '',
      receiverName: '',
      receiverPhone: '',
      province: '',
      city: '',
      district: '',
      detailAddress: '',
      isDefault: false
    },
    region: ['', '', ''],
    isEdit: false,
    fromPage: '' // 添加来源页面标记
  },

  onLoad(options) {
    // 记录来源页面
    this.setData({ 
      fromPage: options.from || 'address-list',
      isEdit: !!options.id
    });

    if (options.id) {
      // 编辑模式
      this.loadAddress(options.id);
    }
  },

  // 加载地址信息
  async loadAddress(id) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    try {
      const res = await api.getAddress(id);
      if (res.success) {
        const address = res.data;
        this.setData({
          address,
          region: [address.province, address.city, address.district]
        });
      } else {
        this.showError('加载地址失败');
      }
    } catch (error) {
      console.error('加载地址失败:', error);
      this.showError('加载地址失败');
    } finally {
      wx.hideLoading();
    }
  },

  // 地区选择器变化
  bindRegionChange(e) {
    this.setData({
      region: e.detail.value,
      'address.province': e.detail.value[0],
      'address.city': e.detail.value[1],
      'address.district': e.detail.value[2]
    });
  },

  // 保存地址
  async saveAddress(e) {
    const values = e.detail.value || {};
    const { region, address, isEdit } = this.data;

    // 表单验证
    if (!values.receiverName || !values.receiverName.trim()) {
      this.showError('请输入收货人姓名');
      return;
    }
    if (!values.receiverPhone || !/^1[3-9]\d{9}$/.test(values.receiverPhone)) {
      this.showError('请输入正确的手机号码');
      return;
    }
    if (!region[0] || !region[1] || !region[2]) {
      this.showError('请选择完整的所在地区');
      return;
    }
    if (!values.detailAddress || !values.detailAddress.trim()) {
      this.showError('请输入详细地址');
      return;
    }

    // 构建地址对象
    const addressData = {
      receiverName: values.receiverName.trim(),
      receiverPhone: values.receiverPhone.trim(),
      province: region[0],
      city: region[1],
      district: region[2],
      detailAddress: values.detailAddress.trim(),
      isDefault: !!values.isDefault
    };

    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    try {
      let res;
      if (isEdit) {
        // 编辑模式：更新地址
        res = await api.updateAddress(address.id, addressData);
      } else {
        // 新增模式：添加地址
        res = await api.addAddress(addressData);
      }

      if (res.success) {
        wx.showToast({
          title: isEdit ? '修改成功' : '添加成功',
          icon: 'success',
          duration: 1500
        });

        // 延迟返回，确保 toast 显示完成
        setTimeout(() => {
          const pages = getCurrentPages();
          const { fromPage } = this.data;
          
          // 如果是从订单确认页或地址选择页进入，且只有一个页面，则跳转到地址列表页
          if ((fromPage === 'checkout' || fromPage === 'select') && pages.length === 1) {
            wx.redirectTo({
              url: '/pages/address/address'
            });
          } else {
            // 返回上一页，并传递新地址信息
            const prevPage = pages[pages.length - 2];
            if (prevPage && (fromPage === 'checkout' || fromPage === 'select')) {
              prevPage.setData({
                selectedAddress: res.data
              });
            }
            wx.navigateBack();
          }
        }, 1500);
      } else {
        this.showError(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存地址失败:', error);
      this.showError(error.message || '保存失败，请稍后重试');
    } finally {
      wx.hideLoading();
    }
  },

  // 显示错误提示
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  },

  // 返回上一页
  goBack() {
    const pages = getCurrentPages();
    const { fromPage } = this.data;
    
    // 如果是从订单确认页或地址选择页进入，且只有一个页面，则跳转到地址列表页
    if ((fromPage === 'checkout' || fromPage === 'select') && pages.length === 1) {
      wx.redirectTo({
        url: '/pages/address/address'
      });
    } else {
      wx.navigateBack();
    }
  }
}) 